package inits

import (
	"doctor-srv/basic/config"
	"doctor-srv/handler/model"
	"fmt"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		config.Conf.Mysql.User,
		config.Conf.Mysql.Password,
		config.Conf.Mysql.Host,
		config.Conf.Mysql.Port,
		config.Conf.Mysql.DBName,
	)

	var err error
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}

	// 自动迁移数据库表结构
	err = config.DB.AutoMigrate(
		&model.Doctor{},
		&model.Patient{},
		&model.Consultation{},
		&model.Medicine{},
		&model.Prescription{},
		&model.PrescriptionItem{},
		&model.MedicineOrder{},
		&model.MedicalRecord{},
		&model.Attachment{},
		&model.ConsultationRating{},
	)
	if err != nil {
		log.Fatalf("Failed to migrate database: %v", err)
	}

	log.Println("Database connected and migrated successfully")
}

